package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strconv"
)

func main() {
	//url分析	"rs16":"https://rpic.douyucdn.cn/live-cover/appCovers/2020/06/03/6766469_20200603124357_small.jpg/dy1"
	url := "https://www.douyu.com/gapi/rkc/directory/mixList/3_1764/1"
	//爬取页面所有所有信息
	result, err := httpGet(url)
	if err != nil {
		fmt.Println("get err", err)
	}

	//解析编译正则

	num := make(chan int)
	ret := regexp.MustCompile(`"rs16":"(?s:(.*?))"`)
	//提取图片url
	alls := ret.FindAllStringSubmatch(result, -1)

	n := len(alls)

	for idx, url := range alls {
		//fmt.Println("url",all[1])
		go saveImg(idx, url[1], num)
	}
	for i := 0; i < n; i++ {
		fmt.Printf("——第%d张图片下载完成——\n", <-num)
	}
}
func saveImg(idx int, url string, num chan int) {
	path := "D:/img/" + strconv.Itoa(idx+1) + ".jpg"
	file, err := os.Create(path)
	if err != nil {
		fmt.Println("creat err", err)
	}
	defer file.Close()

	resp, err1 := http.Get(url)
	if err1 != nil {
		fmt.Println("save err", err1)
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)

	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		file.Write(buf[:n])
	}
	num <- idx + 1
}

//获取一个网页的所有内容
func httpGet(url string) (result string, err error) {
	resp, err1 := http.Get(url)
	if err1 != nil {
		err = err1
		return
	}
	defer resp.Body.Close()
	buf := make([]byte, 4096)

	for {
		n, err2 := resp.Body.Read(buf)
		if n == 0 {
			break
		}
		if err2 != nil && err2 != io.EOF {
			err = err2
			return
		}
		result += string(buf[:n])
	}
	return
}
